//
//  UpdateEngine.swift
//  OnemeetingDemo
//
//  Created by 张衡 on 2020/3/18.
//  Copyright © 2020 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation

class UpdateEngine: NSObject {
    
    static let shared = UpdateEngine()
    
    var isComplete:Bool = false
    var request: DownloadRequest?

    let downUrl = FileManager.default.urls(for: FileManager.SearchPathDirectory.desktopDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)[0]
    let urlString =  "https://www.1meeting.cn/mac/1meeting.dmg"
    
    lazy var indicator: NSProgressIndicator = {
        let view = NSProgressIndicator.init(frame: NSRect.zero)
        view.style = NSProgressIndicator.Style.bar
        view.controlSize = .regular
        view.isIndeterminate = false
        view.minValue = 0.0
        view.maxValue = 100.0
        view.doubleValue = 0.0
        return view
    }()
    
    lazy var loadLab: NSTextField = {
        let lab = NSTextField.label(title: "0.0M/42.0M", textColor: NSColor.black, font: NSFont.systemFont(ofSize: 14))
        return lab
    }()
    
    lazy var accessoryView: NSView = {
        let view = NSView.init(frame: NSRect.init(x: 0, y: 0, width: 300, height: 32))
        return view
    }()
    
    func setupUI() {
        
        self.accessoryView.addSubview(indicator)
        indicator.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(10)
        }
        
        self.accessoryView.addSubview(loadLab)
        loadLab.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.width.equalTo(100)
            make.left.equalTo(0)
            make.height.equalTo(18)
        }
    }
    
    lazy var alert: NSAlert = {
        let alert = NSAlert.init()
        alert.icon = NSImage.imageNamed("logo_128")!
        alert.addButton(withTitle: "取消")
        alert.messageText = "正在下载更新..".localized()
        alert.informativeText = ""
        alert.alertStyle = .warning
        alert.buttons[0].action = #selector(alertBtnAction(senber:))
        alert.buttons[0].target = self
        return alert
    }()
    
    @objc func alertBtnAction(senber:NSButton) {
        
        if self.isComplete == true {
            XQProcess.restartToFile(fileName: self.urlString.lastPathComponent, basicPath: nil)
        }else {
            if self.request != nil {
                self.request?.suspend()
            }
            
            if File.isfileExists(path: downUrl.absoluteString) == false {
                File.removeFilePath(path: downUrl.absoluteString)
            }
            NSApp.endSheet(self.alert.window)
            
        }
    }
 
    
    func loadying(url:String?) {
        
        let u = url==nil ? self.urlString:url!
        self.downLoad(url: u)
        
        self.isComplete = false
        
        self.setupUI()
        
        
        self.alert.accessoryView = self.accessoryView
    
        self.alert.runModal()
        
        /*
        alert.beginSheetModal(for: NSApplication.shared.mainWindow!) { (returnCode) in
            if returnCode == NSApplication.ModalResponse.alertFirstButtonReturn {
                print("")
            }
        }
        */
        
        
    }
    
    func downLoad(url:String) {
        
        self.request = NetworkTool.download(urlString: url, fileBaseUrl: downUrl, closure: { (progress) in
            self.indicator.doubleValue = (progress*100)
            let s = String.init(format: "%.2f", (progress*42))
            self.loadLab.stringValue = s+"M/"+"42M"
            print("正在下载。。。。")
        }) { (data) in
            self.loadLab.stringValue = "42M/42M"
            self.alert.buttons[0].title = "点击安装".localized()
            self.alert.messageText = "下载完成，文件已保存到桌面".localized()
            self.isComplete = true
            self.request = nil
            print("完成")
        }
        
    }
    
    
    func createFile() {
        //在桌面上创建一个文件
        let manager = FileManager.default
        let urlForDocument = manager.urls( for: .desktopDirectory,
                                           in:.userDomainMask)
        let url = urlForDocument[0]
        createFile(name:"test.txt", fileBaseUrl: url)
    }
    
    //根据文件名和路径创建文件
    func createFile(name:String, fileBaseUrl:URL){
        let manager = FileManager.default
         
        let file = fileBaseUrl.appendingPathComponent(name)
        print("文件: \(file)")
        let exist = manager.fileExists(atPath: file.path)
        if !exist {
            //在文件中随便写入一些内容
            let data = Data(base64Encoded:"aGVsbG8gd29ybGQ=" ,options:.ignoreUnknownCharacters)
            let createSuccess = manager.createFile(atPath: file.path,contents:data,attributes:nil)
            print("文件创建结果: \(createSuccess)")
        }
    }
    
    
}

public extension String {
    /// 从url中获取后缀 例：.pdf
    var pathExtension: String {
        guard let url = URL(string: self) else { return "" }
        return url.pathExtension.isEmpty ? "" : ".\(url.pathExtension)"
    }
    /// 从url中获取后缀 例：.pdf
    var lastPathComponent: String {
        guard let url = URL(string: self) else { return "" }
        return url.lastPathComponent.isEmpty ? "" : "\(url.lastPathComponent)"
    }
}
